package com.ucpaas.monitor.service;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import com.alibaba.fastjson.JSONObject;
import com.ucpaas.monitor.common.JsonDto;
import com.ucpaas.monitor.util.CommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.ucpaas.monitor.util.SystemUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MonitorServiceImpl implements MonitorService{
	
	private static final Logger logger = LoggerFactory.getLogger(MonitorServiceImpl.class);
	
	@Value("${remoteAddr}")
	private String remoteAddr;
	
	@Override
	public void getRemoteVM() throws Exception {
		/* 
		* host: 远程机器的ip地址 
		* port: 远程java进程运行的jmxremote端口 
		* 
		*/  
		logger.info("远程地址："+remoteAddr);	
		JMXServiceURL serviceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + remoteAddr + "/jmxrmi");  
		JMXConnector conn = JMXConnectorFactory.connect(serviceURL);  
		MBeanServerConnection mbs = conn.getMBeanServerConnection();  
		  
		logger.info("当前堆内存使用率："+SystemUtils.getHeapMemoryUsage());
		logger.info("当前堆内存使用率百分比："+SystemUtils.getHeapMemoryUsagePercent());
		logger.info("当前非java堆占用率 ："+SystemUtils.getNonHeapMemoryUsage());
		logger.info("当前非java堆占用的百分比 ："+SystemUtils.getNonHeapMemoryUsagePercent());
		logger.info("当前VM线程数 ："+SystemUtils.getThreadCount());
		SystemUtils.printMemoryMx(mbs); 
        
		SystemUtils.printOperatorSysMx(mbs);  
		
		SystemUtils.printRuntimeMxBean(mbs); 
        
		SystemUtils.printThreadMx(mbs);  
        
		SystemUtils.printClassLoadMx(mbs);  
        
		SystemUtils.printCompileMx(mbs);  
        
		SystemUtils.printGcMx(mbs);   
        
		SystemUtils.printMemoryMgrMx(mbs);  
        
		SystemUtils.printMemPoolMx(mbs);  
        
        
        
	}

	/**
	 * 调用脚本执行linux命令
     *  打印进程PID： ps -ef |grep admin-agent|grep -v 'grep'|awk '{print $2}'
	 * @return
	 */
	@Override
	public JsonDto command(JSONObject jsonObj ) throws Exception {
        String bashCommand = jsonObj.getString("command");
        logger.info("====bashCommand==={}",bashCommand);
        JsonDto jsonDto = new JsonDto();
//		String bashCommand = "sh "+ "/opt/ipcc/monitorScript/hello.sh";
		List<String> commands = new ArrayList<String>();
		commands.add("/bin/sh");
		commands.add("-c");
		commands.add(bashCommand);
        String result = null;;
        try{
            result = CommandUtil.run(commands.toArray(new String[commands.size()]));
            logger.info("恭喜执行命令成功:{}",result);
            jsonDto.setCode("0");
            jsonDto.setMsg("Success to call shell's command");
            jsonDto.setData(result.split("\n")[1]);
        }catch (Exception e){
            logger.error("Failed to call shell's command ");
            jsonDto.setCode("-1");
            jsonDto.setMsg("Failed to call shell's command");
        }
		return jsonDto;
	}


}
